package com.imooc.user.controller;

import com.imooc.user.constant.CookieConstant;
import com.imooc.user.constant.RedisConstant;
import com.imooc.user.dataobject.UserInfo;
import com.imooc.user.enums.ResultEnum;
import com.imooc.user.enums.RoleEnum;
import com.imooc.user.service.UserService;
import com.imooc.user.utils.CookieUtil;
import com.imooc.user.utils.ResultVOUtil;
import com.imooc.user.vo.ResultVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 用户登录（买家端和卖家端）
 * @author steve
 * @date 2020/6/25 7:02 上午
 */
@RestController
@RequestMapping("/login")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate template;

    /**
     * 买家登录
     *
     * @param openid
     * @param response 用于设置cookie
     * @return `cookie里设置openid=abc`
     */
    @GetMapping("/buyer")
    public ResultVO buyerLogin(String openid, HttpServletResponse response) {
        UserInfo userInfo = userService.findByOpenid(openid);
        if (userInfo == null) {
            //1. 判断用户为空
            return ResultVOUtil.error(ResultEnum.LOGIN_FAIL.getCode(),ResultEnum.LOGIN_FAIL.getMessage());
        }
        if (!RoleEnum.BUYER.getCode().equals(userInfo.getRole())) {
            //2. 角色权限错误
            return ResultVOUtil.error(ResultEnum.ROLE_ERROR.getCode(), ResultEnum.ROLE_ERROR.getMessage());
        }
        //3.openid设置到cookie,过期时间2小时
        CookieUtil.set(response, CookieConstant.OPENID,openid,CookieConstant.expiry);
        //成功
        return ResultVOUtil.success();
    }

    /**
     * 卖家登录
     * @param openid
     * @param response
     * @return `cookie里设置token=UUID, redis设置key=UUID, value=xyz`
     */
    @GetMapping("/seller")
    public ResultVO sellerLogin(String openid, HttpServletResponse response, HttpServletRequest request) {
        //角色登录成功后，cookie中的token便会固定，不会一直变动
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if (cookie != null &&
                !StringUtils.isEmpty(template.opsForValue().get(String.format(RedisConstant.TOKEN_TEMPLATE,cookie.getValue())))) {
            //判断浏览器获得cookie不为null，并且token的值不为空
            return ResultVOUtil.success();
        }
        UserInfo userInfo = userService.findByOpenid(openid);
        if (userInfo == null) {
            //1. 判断用户为空
            return ResultVOUtil.error(ResultEnum.LOGIN_FAIL.getCode(),ResultEnum.LOGIN_FAIL.getMessage());
        }
        if (!RoleEnum.SELLER.getCode().equals(userInfo.getRole())) {
            //2. 角色权限错误
            return ResultVOUtil.error(ResultEnum.ROLE_ERROR.getCode(), ResultEnum.ROLE_ERROR.getMessage());
        }
        String token = UUID.randomUUID().toString();
        //3. cookie里设置token=UUID
        CookieUtil.set(response,CookieConstant.TOKEN, token,CookieConstant.expiry);

        //4.redis设置key=UUID, value=xyz
        Integer expiry = CookieConstant.expiry;
        template.opsForValue().set(String.format(RedisConstant.TOKEN_TEMPLATE,token)
                ,openid,expiry, TimeUnit.SECONDS);
        return ResultVOUtil.success();
    }

}
